﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using Infrastructure;
using MSIACCSL2.Web.GroupServices;
using MSIACCSL2.Web.ItemServices;
using MSIACCSL2.Web.SubgroupServices;
using MSIACCSL2.Web.WarehouseServices;

namespace MSIACCSL2.Web.ReportPage
{
    public partial class LaporanMutasiStok : System.Web.UI.Page
    {
        private DataAccess<Object> dataAccess;
        private ReportDocument customerReport;

        public LaporanMutasiStok()
        {
            dataAccess = new DataAccess<object>();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
           
            if(! IsPostBack)
            {
                Prepare();
            }else
            {
                LoadReport((DataTable)Cache["dt"]);
            }
        }


        //private void LoadReport(DataTable source)
        //{
        //        var query = Server.UrlDecode(Request.QueryString[0].ToString());
        //        if (source == null)
        //        {
        //            source = dataAccess.GetDataListDataTable(query.Replace("tambah", "+").Replace("persen", "%"));
        //            Cache["dt"] = source;
        //        }
                    
        //        customerReport = new ReportDocument();
        //        string reportPath = string.Empty;

        //        if (Request.QueryString["tipe"].ToString() == "Summary")
        //        {
        //            reportPath = Server.MapPath("~/Report/LapMutasiStokSummary.rpt");
        //        }
        //        else
        //        {
        //            reportPath = Server.MapPath("~/Report/LapMutasiStokDetail.rpt");
        //        }

        //        customerReport.Load(reportPath);
        //        customerReport.SetDataSource(source);
        //        SetParameter();
        //        CrystalReportViewer1.ReportSource = customerReport;
           
        //}


        private void SetParameter()
        {
            var param = new ParameterDiscreteValue();
            param.Value = txtTgl1.Text;
            var paramValue = new ParameterValues();
            paramValue.Add(param);
            customerReport.DataDefinition.ParameterFields["TglStart"].ApplyCurrentValues(paramValue);

            var param2 = new ParameterDiscreteValue();
            param2.Value = txtTgl2.Text;
            var param2Value = new ParameterValues();
            param2Value.Add(param2);
            customerReport.DataDefinition.ParameterFields["TglEnd"].ApplyCurrentValues(param2Value);


            //var param3 = new ParameterDiscreteValue();
            //param3.Value = Request.QueryString["TglSaldoAwal"].ToString();
            //var param3Value = new ParameterValues();
            //param3Value.Add(param3);
            //customerReport.DataDefinition.ParameterFields["TglSaldoAwal"].ApplyCurrentValues(param3Value);
        }

        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);
            this.Unload += Page_Unload;
        }

        void Page_Unload(object sender, EventArgs e)
        {
            if (customerReport != null)
            {
                customerReport.Clone();
                customerReport.Dispose();
            }
        }

        void Prepare()
        {
            var groupClient = new GroupServicesClient();
            var itemClient = new ItemServicesClient();
            var subgroupClient = new SubGroupServiceClient();
            var warehouseClient = new WarehouseServicesClient();

            var groups = groupClient.GetAll();
            cboGroup.Items.Clear();
            cboGroup.Items.Add(new ListItem("All", ""));
            foreach (var groupDto in groups)
            {
                ListItem item = new ListItem(groupDto.GroupName, groupDto.GroupID);
                cboGroup.Items.Add(item);
            }

            var subgroups = subgroupClient.GetAllSubGroup();
            cboSubGroup.Items.Clear();
            cboSubGroup.Items.Add(new ListItem("All", ""));
            foreach (var subgroup in subgroups)
            {
                ListItem item = new ListItem(subgroup.SubGroupName, subgroup.SubGroupID);
                cboSubGroup.Items.Add(item);
            }

            var items = itemClient.GetAllItem();
            cboItem.Items.Clear();
            cboItem.Items.Add(new ListItem("All", ""));
            foreach (var ite in items)
            {
                ListItem item = new ListItem(ite.ItemName, ite.ItemId);
                cboItem.Items.Add(item);
            }

            var warehouses = warehouseClient.GetAllWarehouse();
            cboWarehouse.Items.Clear();
            cboWarehouse.Items.Add(new ListItem("All", ""));
            foreach (var warehouse in warehouses)
            {
                var item = new ListItem(warehouse.WarehouseName, warehouse.KodeWarehouse);
                cboWarehouse.Items.Add(item);
            }
        }

        protected void btnShow_Click(object sender, EventArgs e)
        {
            LoadReport(null);
        }


        void LoadReport(DataTable source)
        {
            StringBuilder sb = new StringBuilder();

            if (string.IsNullOrEmpty(cboWarehouse.SelectedValue))
            {
                sb.Append(" Select ");
                sb.Append(" *,((Coalesce(SaldoAwal,0)) tambah QtyMasuk-QtyKeluar) as QtySisa ");
                sb.Append(" from ");
                sb.Append(" ( ");
                sb.Append(" SELECT ");
                sb.Append(
                    " CASE WHEN (Select Sum(QtyMasuk) - Sum(QtyKeluar) from MutasiStok   where MutasiStok.SerialNumber=i.SerialNumber AND TglMutasi < a.TglMutasi and [TYPE]<>'MutasiWarehouse') IS NULL THEN 0  ");
                sb.Append(" ELSE (Select Sum(QtyMasuk) - Sum(QtyKeluar) from MutasiStok   where MutasiStok.SerialNumber=i.SerialNumber AND TglMutasi < a.TglMutasi and [TYPE]<>'MutasiWarehouse') End ");
                sb.Append(" as SaldoAwal, ");
                sb.Append(" a.Type,a.TglMutasi,CASE When QtyMasuk IS NULL THEN 0 ELSE QtyMasuk END as QtyMasuk,CASE When QtyKeluar IS NULL THEN 0 ELSE QtyKeluar END as QtyKeluar, ");
                sb.Append(" a.SheetMasuk,a.SheetKeluar,a.SheetSisa,a.ReferenceNumber  ,i.*,b.ItemName,c.SubGroupId,c.SubGroupName,d.GroupId,d.GroupName  ");
                sb.Append(" from Inventory i  ");
                sb.Append(" LEFT JOIN   (  ");
                sb.Append(" Select   QtyMasuk,QtyKeluar,[Type],ReferenceNumber,SerialNumber,TglMutasi,SheetMasuk,SheetKeluar,SheetSisa  from MutasiStok  ");
                sb.Append(" Where [TYPE]<>'SaldoAwal' AND CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, TglMutasi)))  ");
                sb.Append(" between '" +
                DateTime.Parse(txtTgl1.Text, new CultureInfo("ID-id")).ToString("yyyy-MM-dd") + "' AND '" +
                DateTime.Parse(txtTgl2.Text, new CultureInfo("ID-id")).ToString("yyyy-MM-dd") + "'  ");
                sb.Append(" AND [TYPE]<>'MutasiWarehouse'    ");
                sb.Append(" ) a on a.SerialNumber = i.SerialNumber  ");
                sb.Append(" LEFT JOIN  Item b on i.ItemID = b.ItemId     ");
                sb.Append(" LEFT JOIN  Subgroup c on b.SubgroupId = c.SubgroupId   ");
                sb.Append(" LEFT JOIN  Groups d on c.GroupId = d.GroupId  ");
                sb.Append(" ) T Where IsStock=1 ");
            }
            else
            {
                sb.Append(" Select * from ( ");
                sb.Append("Select ");
                sb.Append(
                    "Case When (Select Top 1  QtySisa from MutasiStok where MutasiStok.SerialNumber=a.SerialNumber and CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, TglMutasi)))<'" +
                    DateTime.Parse(txtTgl1.Text, new CultureInfo("ID-id")) + "' ");
                sb.Append(" AND KodeWarehouse='" + cboWarehouse.SelectedValue + "') IS NULL Then 0 Else ");
                sb.Append("(Select Top 1  QtySisa from MutasiStok where MutasiStok.SerialNumber=a.SerialNumber and CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, TglMutasi)))<'" +
                    DateTime.Parse(txtTgl2.Text, new CultureInfo("ID-id")) + "' AND KodeWarehouse='" + cboWarehouse.SelectedValue + "') ");
                sb.Append(" End as SaldoAwal,");
                sb.Append(" CASE When QtyMasuk IS NULL THEN 0 ELSE QtyMasuk END as QtyMasuk,CASE When QtyKeluar IS NULL THEN 0 ELSE QtyKeluar END as QtyKeluar,CASE When QtySisa IS NULL THEN 0 ELSE QtySisa END as QtySisa,[Type],ReferenceNumber,TglMutasi,SheetMasuk,SheetKeluar,SheetSisa,i.*,b.ItemName,c.SubGroupId,c.SubGroupName,d.GroupId,d.GroupName ");
                sb.Append(" from Inventory i");
                sb.Append(" Left Join");
                sb.Append(" (");
                sb.Append(" Select QtyMasuk,QtyKeluar,QtySisa,[Type],ReferenceNumber,SerialNumber,TglMutasi,SheetMasuk,SheetKeluar,SheetSisa from MutasiStok  Where [TYPE]<>'SaldoAwal'");
                sb.Append(" AND CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, TglMutasi))) between '" + DateTime.Parse(txtTgl1.Text, new CultureInfo("ID-id")).ToString("yyyy-MM-dd") + "' AND '" + DateTime.Parse(txtTgl2.Text, new CultureInfo("ID-id")).ToString("yyyy-MM-dd") + "'");
                sb.Append(" AND KodeWarehouse='" + cboWarehouse.SelectedValue + "'");
                sb.Append(" ) a on a.SerialNumber = i.SerialNumber ");
                sb.Append(" LEFT JOIN  Item b on i.ItemID = b.ItemId ");
                sb.Append(" LEFT JOIN  Subgroup c on b.SubgroupId = c.SubgroupId ");
                sb.Append(" LEFT JOIN  Groups d on c.GroupId = d.GroupId");
                sb.Append(") T Where IsStock=1 ");
            }

            if (!string.IsNullOrEmpty(txtNoLog.Text))
                sb.AppendFormat(" AND SerialNumber like'persen{0}persen'", txtNoLog.Text);
            if (!string.IsNullOrEmpty(txtKodeMasuk.Text))
                sb.AppendFormat(" AND KodeMasuk like 'persen{0}persen'", txtKodeMasuk.Text);
            if (!string.IsNullOrEmpty(txtKeterangan.Text))
                sb.AppendFormat(" AND [Description] like 'persen{0}persen'", txtKeterangan.Text);
            if (!string.IsNullOrEmpty(txtPallet.Text))
                sb.AppendFormat(" AND KodePallet like 'persen{0}persen'", txtPallet.Text);
            if (!string.IsNullOrEmpty(txtNoBundle.Text))
                sb.AppendFormat(" AND NoBundle ={0}", txtNoBundle.Text);
            if (! string.IsNullOrEmpty(txtPanjang.Text))
                sb.AppendFormat(" AND Panjang >={0} AND Panjang <={1}", txtPanjang.Text, txtPanjang2.Text);
            if (! string.IsNullOrEmpty(txtLebar.Text))
                sb.AppendFormat(" AND Lebar >={0} AND Lebar <={1}", txtLebar.Text, txtLebar2.Text);
            if (! string.IsNullOrEmpty(txtTinggi.Text))
                sb.AppendFormat(" AND SheetSisa >={0} AND SheetSisa <={1}", txtTinggi.Text, txtTinggi2.Text);


            if (cboItem.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
                sb.Append(" AND ItemId in (");

            foreach (ListItem item in cboItem.Items.Cast<ListItem>().Where(x => x.Selected && !string.IsNullOrEmpty(x.Value)))
                sb.AppendFormat("'{0}',", item.Value);

            if (cboItem.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
            {
                sb.Remove(sb.Length - 1, 1);
                sb.Append(")");
            }



            if (cboGroup.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
                sb.Append(" AND GroupID in (");
            foreach (var group in cboGroup.Items.Cast<ListItem>().Where(x => x.Selected && !string.IsNullOrEmpty(x.Value)))
                sb.AppendFormat("'{0}',", group.Value);
            if (cboGroup.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
            {
                sb.Remove(sb.Length - 1, 1);
                sb.Append(")");
            }

            if (cboSubGroup.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
                sb.Append(" AND SubGroupID in (");
            foreach (var group in cboSubGroup.Items.Cast<ListItem>().Where(x => x.Selected && !string.IsNullOrEmpty(x.Value)))
                sb.AppendFormat("'{0}',", group.Value);
            if (cboSubGroup.Items.Cast<ListItem>().Any(item => item.Selected && !string.IsNullOrEmpty(item.Value)))
            {
                sb.Remove(sb.Length - 1, 1);
                sb.Append(")");
            }

            sb.Append(" ORDER BY TglMutasi,SubGroupID,ItemId  ");

            var query = sb.ToString();
            if (source == null)
            {
                source = dataAccess.GetDataListDataTable(query.Replace("tambah", "+").Replace("persen", "%"));
                Cache["dt"] = source;
            }

            customerReport = new ReportDocument();
            string reportPath = string.Empty;

            if (rblTipe.SelectedValue == "Summary")
                reportPath = Server.MapPath("~/Report/LapMutasiStokSummary.rpt");
            else
                reportPath = Server.MapPath("~/Report/LapMutasiStokDetail.rpt");

            customerReport.Load(reportPath);
            customerReport.SetDataSource(source);
            SetParameter();
            CrystalReportViewer1.ReportSource = customerReport;

          
        }

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            DateTime result;
            args.IsValid = DateTime.TryParse(txtTgl1.Text, new System.Globalization.CultureInfo("id-ID"), DateTimeStyles.None, out result) && DateTime.TryParse(txtTgl2.Text, new System.Globalization.CultureInfo("id-ID"),DateTimeStyles.None, out result);

        }
      
    }
}